import {
  CollectionViewer,
  DataSource,
  SelectionChange,
  SelectionModel,
} from '@angular/cdk/collections';
import { FlatTreeControl, TreeControl } from '@angular/cdk/tree';
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { JoblevelService, OrganizationService } from 'sparrow-permission-lib';
import { FlatNode } from 'src/app/domain/flat-node';
import { DynamicDataSourceForNzTreeService } from 'src/app/service/dynamic-data-source-for-nz-tree.service';

import { LevelService } from 'src/app/service/level.service';
import { NzTreeCommonService } from 'src/app/service/nz-tree-common.service';
import { NzTreeGetChildren } from 'src/app/service/nz-tree-get-children';
import { NzTreeGetLevelChildrenService } from 'src/app/service/nz-tree-get-level-children.service';

@Component({
  selector: 'app-level-search',
  templateUrl: './level-search.component.html',
  styleUrls: ['./level-search.component.css'],
})
export class LevelSearchComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private levelService: JoblevelService,
    private orgService: OrganizationService
  ) {}
  dataSource: any;
  hasChild = (_: number, node: FlatNode) => node.expandable;
  treeService: NzTreeCommonService = new NzTreeCommonService();

  ngOnInit(): void {
    let getChildrenService: NzTreeGetChildren =
      new NzTreeGetLevelChildrenService(this.levelService, this.orgService);
    getChildrenService
      .getChildren({
        id: 'root',
        label: 'root',
        level: -1,
        expandable: true,
        type: 'ORG',
      })
      .subscribe(
        (res) => {
          this.dataSource = new DynamicDataSourceForNzTreeService(
            this.treeService.treeControl,
            res,
            getChildrenService
          );
        },
        (error) => {
          this.message.error('初始化失败！' + error);
        }
      );
  }

  selectedLevels: any[] = [];
  onItemSelect(node: any) {
    if (this.selectedLevels.findIndex((f) => f.id === node.id) < 0)
      this.selectedLevels.push(node);
  }

  onClose(node: any) {
    this.selectedLevels = this.selectedLevels.filter((f) => f.id != node.id);
  }
}
